﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using InternshipManagement.Models;
using System.IO;
using InternshipManagement.Helpers;

namespace InternshipManagement.Controllers
{
    [CustomAuthorize]
    public class AnnouncementController : Controller
    {
        DocumentRepository documentRepository = new DocumentRepository();
        AnnouncementRepository announcementRepository = new AnnouncementRepository();
        AccountRepository accountRepository = new AccountRepository();
        //
        // GET: /Announcement/
        [CustomAuthorize(Privileges = UserPrivileges.DisplayAnnouncements)]
        public ActionResult Index(int? page)
        {
            const int pageSize = 10;

            IQueryable<Announcement> announcements = null;
            int? courseID = null;
            if((int)Session["UserTypeID"] == accountRepository.GetUserTypeID("Student"))
                courseID = accountRepository.GetStudent((int)Session["UserID"]).CourseID;
            announcements = announcementRepository.GetReceivedAnnouncements((int)Session["UserTypeID"], (int)Session["UserID"], courseID);

            var paginatedAnnouncements = new PaginatedList<Announcement>(announcements, page ?? 0, pageSize);

            ViewBag.UnRead = announcementRepository.GetUnreadAnnouncements((int)Session["UserTypeID"], (int)Session["UserID"],courseID).ToList();
            return View(paginatedAnnouncements);
        }
        /*
        public ActionResult AdminIndex(int? page)
        {
            const int pageSize = 10;

            IQueryable<Announcement> announcements = null;

            announcements = announcementRepository.GetReceivedAnnouncements((int)Session["UserTypeID"], (int)Session["UserID"]);

            var paginatedAnnouncements = new PaginatedList<Announcement>(announcements, page ?? 0, pageSize);

            ViewBag.UnRead = announcementRepository.GetUnreadAnnouncements((int)Session["UserTypeID"], (int)Session["UserID"]).ToList();
            return View(paginatedAnnouncements);
        }
        */
        [CustomAuthorize(Privileges = UserPrivileges.ListAnnouncements)]
        public ActionResult List(int? page)
        {
            const int pageSize = 10;

            IQueryable<Announcement> announcements = null;

            announcements = announcementRepository.FindAllAnnouncements();

            var paginatedAnnouncements = new PaginatedList<Announcement>(announcements, page ?? 0, pageSize);

            return View(paginatedAnnouncements);
        }

        [CustomAuthorize(Privileges = UserPrivileges.CreateAnnouncement)]
        public ActionResult Create()
        {
            return View("CreateEdit");
        }

        [HttpPost]
        [CustomAuthorize(Privileges = UserPrivileges.CreateAnnouncement)]
        public ActionResult Create(Announcement announcement, FormCollection formvalues, HttpPostedFileBase attachment)
        {

            if (ModelState.IsValid)
            {
                int? docID = documentRepository.saveDocument(attachment, null);
                if (docID.HasValue)
                    announcement.DocumentID = docID;
                announcement.SenderID = (int)Session["UserID"];
                announcement.Status = "A";
                announcement.SentDate = DateTime.Now;
                announcementRepository.AddAnnouncement(announcement);
                announcementRepository.Save();
                if (formvalues["email"] == "true")
                {
                    List<int> userTypeIDs = new List<int>();
                    if (announcement.IsSecretaryReceiving)
                        userTypeIDs.Add(2);
                    if (announcement.IsStudentReceiving)
                        userTypeIDs.Add(4);
                    if (announcement.IsCompanyReceiving)
                        userTypeIDs.Add(3);
                    IQueryable<string> emails = accountRepository.FindAllEmails(userTypeIDs.ToArray());
                    //TODO SEND MAIL
                }
                return RedirectToAction("List");
            }
            return View("CreateEdit", announcement);
        }
        [CustomAuthorize(Privileges = UserPrivileges.EditAnnouncement)]
        public ActionResult Edit(int id)
        {
            Announcement announcement = announcementRepository.GetAnnouncement(id);
            if (announcement == null)
            {
                return View("ShowMessage", "Announcement does now exists");
            }
            return View("CreateEdit", announcement);
        }

        [HttpPost]
        [CustomAuthorize(Privileges = UserPrivileges.EditAnnouncement)]
        public ActionResult Edit(int id, Announcement announcement, FormCollection formvalues, HttpPostedFileBase attachment)
        {

            if (ModelState.IsValid)
            {
                Announcement deletedannouncement = announcementRepository.GetAnnouncement(id);
                if (deletedannouncement == null)
                {
                    return View("ShowMessage", "Announcement does now exists");
                }
                deletedannouncement.Status = "P";

                int? docID = documentRepository.saveDocument(attachment, null);
                if (docID.HasValue)
                    announcement.DocumentID = docID;
                announcement.SenderID = (int)Session["UserID"];
                announcement.Status = "A";
                announcement.SentDate = DateTime.Now;
                announcementRepository.AddAnnouncement(announcement);
                announcementRepository.Save();
                if (formvalues["email"] == "true")
                {
                    List<int> userTypeIDs = new List<int>();
                    if (announcement.IsSecretaryReceiving)
                        userTypeIDs.Add(2);
                    if (announcement.IsStudentReceiving)
                        userTypeIDs.Add(4);
                    if (announcement.IsCompanyReceiving)
                        userTypeIDs.Add(3);
                    IQueryable<string> emails = accountRepository.FindAllEmails(userTypeIDs.ToArray());
                    //TODO SEND MAIL
                }
                return RedirectToAction("List");
            }
            return View("CreateEdit", announcement);
        }
        [CustomAuthorize(Privileges = UserPrivileges.DeleteAnnouncement)]
        public ActionResult Delete(int id)
        {
            Announcement announcement = announcementRepository.GetAnnouncement(id);
            announcement.Status = "P";
            announcementRepository.Save();
            return RedirectToAction("List");
        }

        [CustomAuthorize(Privileges = UserPrivileges.DisplayAnnouncements)]
        public JsonResult MarkAsRead(int ID)
        {
            if (!announcementRepository.ReadAnnouncementExist(ID, (int)Session["UserID"]))
            {
                ReadAnnouncement readAnnouncement = new ReadAnnouncement();
                readAnnouncement.AnnouncementID = ID;
                readAnnouncement.UserID = (int)Session["UserID"];
                announcementRepository.AddReadAnnouncement(readAnnouncement);
                announcementRepository.Save();
            }
            return Json(new { Result = true });
        }

    }
}
